﻿using IOA.MES.Business;
using IOA.MES.ClientApi.App_Start;
using IOA.MES.DataAccess.VModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace IOA.MES.ClientApi
{
    public class BaseEnv
    {
        private static object lockObj = new object();
        /// <summary>
        /// 登录令牌
        /// </summary>
        public static string Token
        {
            get
            {
                return GetHeader("Token");
            }
        }

        /// <summary>
        /// 登录令牌
        /// </summary>
        public static VUser User
        {
            get
            {
                return new UserMgr().GetUserByToken(Token);
            }
        }

        /// <summary>
        /// 客户端IP
        /// </summary>
        public static string ClientIP
        {
            get
            {
                string ipv4 = String.Empty,
                    clientIp = HttpContext.Current.Request.ServerVariables["HTTP_VIA"] == null ? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                foreach (var ip in Dns.GetHostAddresses(clientIp))
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4 = ip.ToString();
                        break;
                    }
                }
                if (ipv4 != string.Empty)
                {
                    return ipv4;
                }
                foreach (var ip in Dns.GetHostEntry(clientIp).AddressList)
                {
                    if (ip.AddressFamily.ToString() == "InterNetwork")
                    {
                        ipv4 = ip.ToString();
                        break;
                    }
                }

                return ipv4;
            }
        }

        /// <summary>
        /// 车间代码
        /// </summary>
        public static string WorkshopCode
        {
            get
            {
                return GetHeader("WorkshopCode");
            }
        }

        /// <summary>
        /// 获取Header
        /// </summary>
        public static string GetHeader(string key)
        {
            key = HttpContext.Current.Request.Headers.AllKeys.FirstOrDefault(_ => string.Equals(key, _, StringComparison.CurrentCultureIgnoreCase));
            var value = string.IsNullOrWhiteSpace(key) ? string.Empty : HttpContext.Current.Request.Headers[key].ToString().Trim();
            return value ?? string.Empty;
        }

        /// <summary>
        /// 错误代码
        /// </summary>
        public static List<LangPackage> LangPackages { get; set; }

        /// <summary>
        /// 获取错误信息
        /// </summary>
        public static string GetErrMsg(int errCode, string errParas = "")
        {
            lock (lockObj)
            {
                if (BaseEnv.LangPackages == null || !BaseEnv.LangPackages.Any())
                {
                    BaseEnv.LangPackages = new List<LangPackage>();
                    var langFiles = Directory.GetFiles($"{AppDomain.CurrentDomain.BaseDirectory}res");
                    var sortedFiles = new List<string>();
                    if (langFiles.Any(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "vn", StringComparison.CurrentCultureIgnoreCase)))
                    {
                        sortedFiles.Add(langFiles.FirstOrDefault(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "vn", StringComparison.CurrentCultureIgnoreCase)));
                    }
                    if (langFiles.Any(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "zh_CN", StringComparison.CurrentCultureIgnoreCase)))
                    {
                        sortedFiles.Add(langFiles.FirstOrDefault(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "zh_CN", StringComparison.CurrentCultureIgnoreCase)));
                    }
                    if (langFiles.Any(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "en", StringComparison.CurrentCultureIgnoreCase)))
                    {
                        sortedFiles.Add(langFiles.FirstOrDefault(_ => string.Equals(Path.GetFileNameWithoutExtension(_), "en", StringComparison.CurrentCultureIgnoreCase)));
                    }
                    foreach (var langFile in sortedFiles)
                    {
                        var jsonStr = File.ReadAllText(langFile, Encoding.UTF8);
                        BaseEnv.LangPackages.Add(JsonConvert.DeserializeObject<LangPackage>(jsonStr));
                    }
                }
            }
            var sbMsg = new StringBuilder();
            foreach (var lang in BaseEnv.LangPackages)
            {
                var err = lang.package.FirstOrDefault(_ => _.Key == errCode);
                if (err.Value != null)
                {
                    sbMsg.AppendLine(err.Value);
                }
            }
            return sbMsg.ToString().TrimEnd(new[] { '\r', '\n' }) + (string.IsNullOrWhiteSpace(errParas) ? string.Empty : $"：\r\n{errParas}");
        }
    }
}
